import { NextRequest, NextResponse } from 'next/server';
import Keyv from 'keyv';
import { KeyvFile } from 'keyv-file';
import path from 'path';

// 初始化 Keyv 存儲 - 使用絕對路徑指向 API 目錄下的 database.json
const keyv = new Keyv({
  store: new KeyvFile({ 
    filename: path.join(process.cwd(), 'src/data/database.json')
  })
});


// 初始化數據
async function initializeData() {
  const existingData = await keyv.get('pages');
  
  // 如果沒有數據，從 database.json 文件初始化
  if (!existingData || existingData.length === 0) {
    const fs = require('fs');
    const path = require('path');
    
    try {
      const dbPath = path.join(process.cwd(), 'src/data/database.json');
      const rawData = fs.readFileSync(dbPath, 'utf8');
      const initialData = JSON.parse(rawData);
      
      // 將數據存儲到 Keyv
      await keyv.set('pages', initialData);
      console.log('數據已初始化:', initialData.length, '個頁面');
    } catch (error) {
      console.error('初始化數據失敗:', error);
    }
  }
}

// 獲取所有頁面數據
export async function GET(request: NextRequest) {
  try {
    // 確保數據已初始化
    await initializeData();
    
    const url = new URL(request.url);
    const id = url.searchParams.get('id');
    
    const pages = await keyv.get('pages') || [];
    
    // 如果提供了 id 參數，返回特定頁面
    if (id) {
      const page = pages.find((p: any) => p.id === parseInt(id));
      if (!page) {
        return NextResponse.json(
          { error: '頁面不存在' },
          { status: 404 }
        );
      }
      return NextResponse.json({
        success: true,
        data: page
      });
    }
    
    // 返回所有頁面
    return NextResponse.json({
      success: true,
      data: pages
    });
  } catch (error) {
    return NextResponse.json(
      { error: '獲取數據失敗', details: error },
      { status: 500 }
    );
  }
}

// 更新頁面內容
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { id, content } = body;
    
    if (!id || content === undefined) {
      return NextResponse.json(
        { error: '缺少必要參數 id 或 content' },
        { status: 400 }
      );
    }
    
    await initializeData();
    const pages = await keyv.get('pages') || [];
    
    const pageIndex = pages.findIndex((p: any) => p.id === parseInt(id));
    if (pageIndex === -1) {
      return NextResponse.json(
        { error: '頁面不存在' },
        { status: 404 }
      );
    }
    
    // 更新內容
    pages[pageIndex].content = typeof content === 'string' ? content : JSON.stringify(content);
    
    await keyv.set('pages', pages);
    
    return NextResponse.json({
      success: true,
      message: '更新成功',
      data: pages[pageIndex]
    });
  } catch (error) {
    return NextResponse.json(
      { error: '更新失敗', details: error },
      { status: 500 }
    );
  }
}

// 創建新頁面（雖然數據固定，但保留此功能以備將來使用）
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, path, content = '{}' } = body;
    
    if (!name || !path) {
      return NextResponse.json(
        { error: '缺少必要參數 name 或 path' },
        { status: 400 }
      );
    }
    
    await initializeData();
    const pages = await keyv.get('pages') || [];
    
    // 檢查路徑是否已存在
    const existingPage = pages.find((p: any) => p.path === path);
    if (existingPage) {
      return NextResponse.json(
        { error: '路徑已存在' },
        { status: 409 }
      );
    }
    
    // 生成新 ID
    const newId = Math.max(...pages.map((p: any) => p.id)) + 1;
    
    const newPage = {
      id: newId,
      name,
      path,
      content: typeof content === 'string' ? content : JSON.stringify(content)
    };
    
    pages.push(newPage);
    await keyv.set('pages', pages);
    
    return NextResponse.json({
      success: true,
      message: '創建成功',
      data: newPage
    }, { status: 201 });
  } catch (error) {
    return NextResponse.json(
      { error: '創建失敗', details: error },
      { status: 500 }
    );
  }
}

// 刪除頁面
export async function DELETE(request: NextRequest) {
  try {
    const url = new URL(request.url);
    const id = url.searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { error: '缺少必要參數 id' },
        { status: 400 }
      );
    }
    
    await initializeData();
    const pages = await keyv.get('pages') || [];
    
    const pageIndex = pages.findIndex((p: any) => p.id === parseInt(id));
    if (pageIndex === -1) {
      return NextResponse.json(
        { error: '頁面不存在' },
        { status: 404 }
      );
    }
    
    const deletedPage = pages.splice(pageIndex, 1)[0];
    await keyv.set('pages', pages);
    
    return NextResponse.json({
      success: true,
      message: '刪除成功',
      data: deletedPage
    });
  } catch (error) {
    return NextResponse.json(
      { error: '刪除失敗', details: error },
      { status: 500 }
    );
  }
}

/**
 * @swagger
 * /api/page_manage:
 *   get:
 *     summary: 獲取頁面數據
 *     description: 獲取所有頁面數據或根據 ID 獲取特定頁面
 *     parameters:
 *       - in: query
 *         name: id
 *         schema:
 *           type: integer
 *         description: 頁面 ID（可選）
 *     responses:
 *       200:
 *         description: 成功獲取數據
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   oneOf:
 *                     - type: array
 *                       items:
 *                         $ref: '#/components/schemas/Page'
 *                     - $ref: '#/components/schemas/Page'
 *       404:
 *         description: 頁面不存在
 *       500:
 *         description: 服務器錯誤
 *   
 *   put:
 *     summary: 更新頁面內容
 *     description: 根據 ID 更新頁面的內容
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - id
 *               - content
 *             properties:
 *               id:
 *                 type: integer
 *                 description: 頁面 ID
 *               content:
 *                 type: string
 *                 description: 頁面內容（JSON 字符串）
 *     responses:
 *       200:
 *         description: 更新成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/Page'
 *       400:
 *         description: 缺少必要參數
 *       404:
 *         description: 頁面不存在
 *       500:
 *         description: 服務器錯誤
 *   
 *   post:
 *     summary: 創建新頁面
 *     description: 創建一個新的頁面
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - name
 *               - path
 *             properties:
 *               name:
 *                 type: string
 *                 description: 頁面名稱
 *               path:
 *                 type: string
 *                 description: 頁面路徑
 *               content:
 *                 type: string
 *                 description: 頁面內容（JSON 字符串）
 *                 default: "{}"
 *     responses:
 *       201:
 *         description: 創建成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/Page'
 *       400:
 *         description: 缺少必要參數
 *       409:
 *         description: 路徑已存在
 *       500:
 *         description: 服務器錯誤
 *   
 *   delete:
 *     summary: 刪除頁面
 *     description: 根據 ID 刪除頁面
 *     parameters:
 *       - in: query
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 頁面 ID
 *     responses:
 *       200:
 *         description: 刪除成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/Page'
 *       400:
 *         description: 缺少必要參數
 *       404:
 *         description: 頁面不存在
 *       500:
 *         description: 服務器錯誤
 * 
 * components:
 *   schemas:
 *     Page:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 頁面 ID
 *         name:
 *           type: string
 *           description: 頁面名稱
 *         path:
 *           type: string
 *           description: 頁面路徑
 *         content:
 *           type: string
 *           description: 頁面內容（JSON 字符串）
 *       example:
 *         id: 1
 *         name: "首页"
 *         path: "/home"
 *         content: "{}"
 */